﻿using System;
using System.Collections.Generic;
using System.Linq;
using Atmk.WaterMeter.MIS.Base;
using Atmk.WaterMeter.MIS.Common;
using Atmk.WaterMeter.MIS.Commons;
using Atmk.WaterMeter.MIS.Commons.Interfaces.Logic;
using Atmk.WaterMeter.MIS.Commons.Utils;
using Atmk.WaterMeter.MIS.Datas;
using Atmk.WaterMeter.MIS.Models.ModelPuls;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;

namespace Atmk.WaterMeter.MIS.Controllers
{
    /// <summary>
    ///     分析模块接口
    /// </summary>
    [Authorize]
    public class AnalysisController : BaseApiController
    {
        private static ILogger<AnalysisController> _logger;
        private readonly TokenHelper _tokenHelper;

        /// <inheritdoc />
        public AnalysisController(
            ILogger<AnalysisController> logger,
            TokenHelper tokenHelper)
        {
            _logger = logger;
            _tokenHelper = tokenHelper;
        }

        /// <summary>
        ///     统计日/月用量统计列表
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        [HttpPost("/api/{X-Version}/Analysis/Dosage/Date")]
        public IActionResult GetDosageByDate([FromBody] dynamic obj)
        {
            var token = _tokenHelper.GetTokenByHttpContext();
            //验证用户信息

            try
            {
                return Ok(new
                {
                    errcode = 0,
                    msg = "ok"
                    //data = AnalysisMock.GetDosageByDate(obj,token.payload.id)
                });
            }
            catch (Exception e)
            {
                return Ok(new
                {
                    errcode = 1,
                    msg = $"获取数据错误,错误:{e.Message}"
                });
            }
        }

        /// <summary>
        ///     统计指定时间日均用量统计列表
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        [HttpPost("/api/{X-Version}/Analysis/Dosage/AvageDay")]
        public IActionResult GetDosageAvageDay([FromBody] dynamic obj)
        {
            var token = _tokenHelper.GetTokenByHttpContext();
            //验证用户信息

            try
            {
                return Ok(new
                {
                    errcode = 0,
                    msg = "ok"
                    //data = AnalysisMock.GetDosageAvageDay(obj, token.payload.id)
                });
            }
            catch (Exception e)
            {
                return Ok(new
                {
                    errcode = 1,
                    msg = $"获取数据错误,错误:{e.Message}"
                });
            }
        }

        /// <summary>
        ///     按主片区统计一定时间用量
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        [HttpPost("/api/{X-Version}/Analysis/Dosage/District")]
        public IActionResult GetDosageDistrict([FromBody] dynamic obj)
        {
            var token = _tokenHelper.GetTokenByHttpContext();
            //验证用户信息

            try
            {
                return Ok(new
                {
                    errcode = 0,
                    msg = "ok"
                    //data = AnalysisMock.GetDosageByDistrict(obj, token.payload.id)
                });
            }
            catch (Exception e)
            {
                return Ok(new
                {
                    errcode = 1,
                    msg = $"获取数据错误,错误:{e.Message}"
                });
            }
        }

        /// <summary>
        ///     按年统计各片区用量
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        [HttpPost("/api/{X-Version}/Analysis/Dosage/Year")]
        public IActionResult GetDosageYear([FromBody] dynamic obj)
        {
            var token = _tokenHelper.GetTokenByHttpContext();
            //验证用户信息

            try
            {
                return Ok(new
                {
                    errcode = 0,
                    msg = "ok"
                    //data = AnalysisMock.GetDosageDistrictYear(obj, token.payload.id)
                });
            }
            catch (Exception e)
            {
                return Ok(new
                {
                    errcode = 1,
                    msg = $"获取数据错误,错误:{e.Message}"
                });
            }
        }

        /// <summary>
        ///     按用量区间统计
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        [HttpPost("/api/{X-Version}/Analysis/Dosage/Interval")]
        public IActionResult GetDosageInterval([FromBody] dynamic obj)
        {
            var token = _tokenHelper.GetTokenByHttpContext();
            //验证用户信息

            try
            {
                return Ok(new
                {
                    errcode = 0,
                    msg = "ok"
                    //data = AnalysisMock.GetDosageInterval(obj, token.payload.id)
                });
            }
            catch (Exception e)
            {
                return Ok(new
                {
                    errcode = 1,
                    msg = $"获取数据错误,错误:{e.Message}"
                });
            }
        }

        /// <summary>
        ///     抄控指令成功率
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        [HttpPost("/api/{X-Version}/Analysis/Commands/SuccessRate")]
        public IActionResult GetSuccessRate([FromHeader] dynamic obj)
        {
            var token = _tokenHelper.GetTokenByHttpContext();
            //验证用户信息

            try
            {
                return Ok(new
                {
                    errcode = 0,
                    msg = "ok"
                    //data = AnalysisMock.GetCommandSuccessRate(obj, token.payload.id)
                });
            }
            catch (Exception e)
            {
                return Ok(new
                {
                    errcode = 1,
                    msg = $"获取数据错误,错误:{e.Message}"
                });
            }
        }


        /// <summary>
        ///  日用量统计
        /// </summary>

        [HttpGet("/api/{X-Version}/Analysis/GetDosageddList")]
        public IActionResult GetDosageddList(int page, string nodeType, string id)
        {
            try
            {
                var token = _tokenHelper.GetTokenByHttpContext();
                //var userid = new Guid(token.payload.id);
                using (var _context = ContextBuilder.Build())
                {
                    try
                    {
                        var total_districts = _context.District.Where(m => m.ProjectId == token.payload.areaid).ToList();
                        var total_owners = _context.Owner.ToList();
                        var total_meters = _context.Meter.Where(m => m.ProjectId == token.payload.areaid).ToList();
                        var list = new List<object>();
                        var settlementDays = _context.SettlementDay.Where(m => m.ReadTime > DateTime.Now.AddDays(-1));
                        foreach (var item in settlementDays)
                        {
                            var tempmeter = total_meters.FirstOrDefault(m1 => m1.CtdeviceId == item.CtdeviceId);
                            var tempdistrict = total_districts.FirstOrDefault(m => m.Id == tempmeter?.DistrictId);
                            list.Add(new
                            {
                                district = tempdistrict?.Name,
                                MeterNumber = tempmeter?.MeterNumber,
                                dosage = item.Dosage.ToString("f2"),
                                readTime = item.ReadTime.ToString("yyyy-MM-dd")
                            });
                        }
                        var result_list = PaginatedList<object>.Create(list, page, 20);
                        return Ok(new
                        {
                            errcode = 0,
                            msg = "ok",
                            data = new
                            {
                                total = settlementDays.Count(),
                                pageSize = 20,
                                list = result_list
                            }
                        });
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                }
            }
            catch (Exception ex)
            {
                return Ok(new { errcode = 1, msg = ex.ToString() });
            }
        }

        /// <summary>
        ///  月用量统计
        /// </summary>

        [HttpGet("/api/{X-Version}/Analysis/GetDosagemmList")]
        public IActionResult GetDosagemmList(int page, string nodeType, string id)
        {
            try
            {
                var token = _tokenHelper.GetTokenByHttpContext();
                //var userid = new Guid(token.payload.id);
                using (var _context = ContextBuilder.Build())
                {
                    try
                    {
                        var total_districts = _context.District.Where(m => m.ProjectId == token.payload.areaid).ToList();
                        var total_owners = _context.Owner.ToList();
                        var total_meters = _context.Meter.Where(m => m.ProjectId == token.payload.areaid).ToList();
                        var list = new List<object>();
                        var settlementDays = _context.SettlementDay.Where(m => m.ReadTime > DateTime.Now.AddDays(-2));
                        foreach (var item in settlementDays)
                        {
                            var tempmeter = total_meters.FirstOrDefault(m1 => m1.CtdeviceId == item.CtdeviceId);
                            var tempdistrict = total_districts.FirstOrDefault(m => m.Id == tempmeter?.DistrictId);
                            list.Add(new
                            {
                                district = tempdistrict?.Name,
                                MeterNumber = tempmeter?.MeterNumber,
                                dosage = item.Dosage.ToString("f2"),
                                readTime = item.ReadTime.ToString("yyyy-MM")
                            });
                        }
                        var result_list = PaginatedList<object>.Create(list, page, 20);
                        return Ok(new
                        {
                            errcode = 0,
                            msg = "ok",
                            data = new
                            {
                                total = settlementDays.Count(),
                                pageSize = 20,
                                list = result_list
                            }
                        });
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                }
            }
            catch (Exception ex)
            {
                return Ok(new { errcode = 1, msg = ex.ToString() });
            }
        }

        /// <summary>
        ///  年用量统计
        /// </summary>
        [HttpGet("/api/{X-Version}/Analysis/GetDosageyyyyList")]
        public IActionResult GetDosageyyyyList(int page, string nodeType, string id)
        {
            try
            {
                var token = _tokenHelper.GetTokenByHttpContext();
                //var userid = new Guid(token.payload.id);
                using (var _context = ContextBuilder.Build())
                {
                    try
                    {
                        var total_districts = _context.District.Where(m => m.ProjectId == token.payload.areaid).ToList();
                        var total_owners = _context.Owner.ToList();
                        var total_meters = _context.Meter.Where(m => m.ProjectId == token.payload.areaid).ToList();
                        var list = new List<object>();
                        var settlementDays = _context.SettlementDay.Where(m => m.ReadTime > DateTime.Now.AddDays(-2));
                        foreach (var item in settlementDays)
                        {
                            var tempmeter = total_meters.FirstOrDefault(m1 => m1.CtdeviceId == item.CtdeviceId);
                            var tempdistrict = total_districts.FirstOrDefault(m => m.Id == tempmeter?.DistrictId);
                            list.Add(new
                            {
                                district = tempdistrict?.Name,
                                MeterNumber = tempmeter?.MeterNumber,
                                dosage = item.Dosage.ToString("f2"),
                                readTime = item.ReadTime.Year
                            });
                        }
                        var result_list = PaginatedList<object>.Create(list, page, 20);
                        return Ok(new
                        {
                            errcode = 0,
                            msg = "ok",
                            data = new
                            {
                                total = settlementDays.Count(),
                                pageSize = 20,
                                list = result_list
                            }
                        });
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                }
            }
            catch (Exception ex)
            {
                return Ok(new { errcode = 1, msg = ex.ToString() });
            }
        }

        /// <summary>
        ///  用量突增突减
        /// </summary>
        [HttpPost]
        public IActionResult GetDosagetztjList(int page, string nodeType, string id)
        {
            try
            {
                var token = _tokenHelper.GetTokenByHttpContext();
                //var userid = new Guid(token.payload.id);
                using (var _context = ContextBuilder.Build())
                {
                    try
                    {
                        var total_districts = _context.District.Where(m => m.ProjectId == token.payload.areaid).ToList();
                        var total_owners = _context.Owner.ToList();
                        var total_meters = _context.Meter.Where(m => m.ProjectId == token.payload.areaid).ToList();
                        var list = new List<object>();
                        var settlementDays = _context.SettlementDay.Where(m => m.Dosage>10);
                        var set_group=settlementDays.GroupBy(m => m.CtdeviceId);
                        foreach (var item in set_group)
                        {
                            var tempmeter = total_meters.FirstOrDefault(m1 => m1.CtdeviceId == item.Key);
                            var tempdistrict = total_districts.FirstOrDefault(m => m.Id == tempmeter?.DistrictId);
                            list.Add(new
                            {
                                district = tempdistrict?.Name,
                                meterNumber = tempmeter?.MeterNumber,
                                dosage = item.Sum(m=>m.Dosage).ToString("f2"),
                                zhouqi = 30,
                                avgdosage=item.Average(m => m.Dosage).ToString("f2"),
                                readTime= item.FirstOrDefault()?.ReadTime.ToString("yyyy-MM-dd HH:mm")
                            });
                        }
                        var result_list = PaginatedList<object>.Create(list, page, 20);
                        return Ok(new
                        {
                            errcode = 0,
                            msg = "ok",
                            data = new
                            {
                                total = settlementDays.Count(),
                                pageSize = 20,
                                list = result_list
                            }
                        });
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                }
            }
            catch (Exception ex)
            {
                return Ok(new { errcode = 1, msg = ex.ToString() });
            }
        }

        /// <summary>
        ///  用量分析
        /// </summary>
        [HttpGet("/api/{X-Version}/Analysis/GetDosageanalyzeList")]
        public IActionResult GetDosageanalyzeList(int page, string nodeType, string id)
        {
            try
            {
                var token = _tokenHelper.GetTokenByHttpContext();
                //var userid = new Guid(token.payload.id);
                using (var _context = ContextBuilder.Build())
                {
                    try
                    {
                        var total_districts = _context.District.Where(m => m.ProjectId == token.payload.areaid).ToList();
                        var total_owners = _context.Owner.ToList();
                        var total_meters = _context.Meter.Where(m => m.ProjectId == token.payload.areaid).ToList();
                        var list = new List<object>();
                        var settlementDays = _context.SettlementDay.Where(m => m.ReadTime > DateTime.Now.AddMonths(-1));
                        var set_group = settlementDays.GroupBy(m => m.CtdeviceId);
                        foreach (var item in set_group)
                        {
                            var tempmeter = total_meters.FirstOrDefault(m1 => m1.CtdeviceId == item.Key);
                            var tempdistrict = total_districts.FirstOrDefault(m => m.Id == tempmeter?.DistrictId);
                            list.Add(new
                            {
                                district = tempdistrict?.Name,
                                MeterNumber = tempmeter?.MeterNumber,
                                dosage = item.Sum(m => m.Dosage).ToString("f2"),
                                zhouqi = 30,
                                avgdosage = item.Average(m => m.Dosage).ToString("f2"),
                                readTime = item.FirstOrDefault()?.ReadTime.ToString("yyyy-MM")
                            });
                        }
                        var result_list = PaginatedList<object>.Create(list, page, 20);
                        return Ok(new
                        {
                            errcode = 0,
                            msg = "ok",
                            data = new
                            {
                                total = settlementDays.Count(),
                                pageSize = 20,
                                list = result_list
                            }
                        });
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                }
            }
            catch (Exception ex)
            {
                return Ok(new { errcode = 1, msg = ex.ToString() });
            }
        }

        /// <summary>
        ///  用户缴费统计
        /// </summary>
        //[HttpPost("/api/{X-Version}/Analysis/GetUserPayReportList")]
        [HttpPost]
        public IActionResult GetUserPayReportList([FromBody]PageEntity pe)
        {
            try
            {
                var token = _tokenHelper.GetTokenByHttpContext();
                //var userid = new Guid(token.payload.id);
                using (var _context = ContextBuilder.Build())
                {
                    try
                    {
                        var orders = _context.OrderDetail.Where(m => m.Money > 0).OrderByDescending(m=>m.CreateTime).Skip((pe.page-1)*20).Take(20).ToList();
                        var total_owners = _context.Owner.ToList();

                        var list_r = new List<object>();
                        var settlementDays = _context.SettlementDay.Where(m => m.ReadTime > DateTime.Now.AddMonths(-1));
                        var set_group = settlementDays.GroupBy(m => m.CtdeviceId);

                        foreach (var item in orders)
                        {
                            var owner = total_owners.FirstOrDefault(m => m.Id == item.OwnerId);
                            list_r.Add(new
                            {
                                ownerName = owner?.Name,
                                mobile = owner?.Mobile,
                                rechargeChannels = item.RechargeChannels,
                                money = item.Money,
                                date=item.CreateTime.ToString("yyyy-MM-dd")
                            });
                        }
                        //var result_list = PaginatedList<object>.Create(list, pe.page, 20);
                        return Ok(new
                        {
                            errcode = 0,
                            msg = "ok",
                            data = new
                            {
                                total = orders.Count(),
                                pageSize = 20,
                                list = list_r
                            }
                        });
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                }
            }
            catch (Exception ex)
            {
                return Ok(new { errcode = 1, msg = ex.ToString() });
            }
        }

        /// <summary>
        ///  用户扣费统计
        /// </summary>
        //[HttpPost("/api/{X-Version}/Analysis/GetUserPayReportList")]
        [HttpPost]
        public IActionResult GetUserFeeReportList([FromBody]PageEntity pe)
        {
            try
            {
                var token = _tokenHelper.GetTokenByHttpContext();
                //var userid = new Guid(token.payload.id);
                using (var _context = ContextBuilder.Build())
                {
                    try
                    {
                        var orders = _context.OrderDetail.Where(m => m.Money < 0).OrderByDescending(m => m.CreateTime).Skip((pe.page - 1) * 20).Take(20).ToList();
                        var total_owners = _context.Owner.ToList();

                        var list_r = new List<object>();
                        var settlementDays = _context.SettlementDay.Where(m => m.ReadTime > DateTime.Now.AddMonths(-1));
                        var set_group = settlementDays.GroupBy(m => m.CtdeviceId);

                        foreach (var item in orders)
                        {
                            var owner = total_owners.FirstOrDefault(m => m.Id == item.OwnerId);
                            list_r.Add(new
                            {
                                ownerName = owner?.Name,
                                mobile = owner?.Mobile,
                                rechargeChannels = item.RechargeChannels,
                                money = item.Money,
                                date = item.CreateTime.ToString("yyyy-MM-dd")
                            });
                        }
                        //var result_list = PaginatedList<object>.Create(list, pe.page, 20);
                        return Ok(new
                        {
                            errcode = 0,
                            msg = "ok",
                            data = new
                            {
                                total = orders.Count(),
                                pageSize = 20,
                                list = list_r
                            }
                        });
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                }
            }
            catch (Exception ex)
            {
                return Ok(new { errcode = 1, msg = ex.ToString() });
            }
        }

        /// <summary>
        ///  日收费统计
        /// </summary>
        //[HttpPost("/api/{X-Version}/Analysis/GetUserPayReportList")]
        [HttpPost]
        public IActionResult GetDaypayReportList([FromBody]PageEntity pe)
        {
            try
            {
                var token = _tokenHelper.GetTokenByHttpContext();
                //var userid = new Guid(token.payload.id);
                using (var _context = ContextBuilder.Build())
                {
                    try
                    {
                        var orders_group = _context.OrderDetail.Where(m => m.Money > 0).GroupBy(m=>Convert.ToDateTime(m.CreateTime).ToString("yyyy-MM-dd"));
                        //var total_owners = _context.Owner.ToList();

                        var list = new List<object>();
                        //var settlementDays = _context.SettlementDay.Where(m => m.ReadTime > DateTime.Now.AddMonths(-1));
                        //var set_group = settlementDays.GroupBy(m => m.CtdeviceId);

                        foreach (var item in orders_group)
                        {
                            list.Add(new
                            {
                                users= item.GroupBy(m=>m.OwnerId).Count(),
                                time= item.Count(),
                                totalMoney = item.Sum(m=>m.Money),
                                date = item.Key
                            });
                        }
                        var result_list = PaginatedList<object>.Create(list, pe.page, 20);
                        return Ok(new
                        {
                            errcode = 0,
                            msg = "ok",
                            data = new
                            {
                                total = orders_group.Count(),
                                pageSize = 20,
                                list = result_list
                            }
                        });
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                }
            }
            catch (Exception ex)
            {
                return Ok(new { errcode = 1, msg = ex.ToString() });
            }
        }

        /// <summary>
        ///  月收费统计
        /// </summary>
        //[HttpPost("/api/{X-Version}/Analysis/GetUserPayReportList")]
        [HttpPost]
        public IActionResult GetMonthpayReportList([FromBody]PageEntity pe)
        {
            try
            {
                var token = _tokenHelper.GetTokenByHttpContext();
                //var userid = new Guid(token.payload.id);
                using (var _context = ContextBuilder.Build())
                {
                    try
                    {
                        var orders_group = _context.OrderDetail.Where(m => m.Money > 0).GroupBy(m => Convert.ToDateTime(m.CreateTime).ToString("yyyy-MM"));
                        var list = new List<object>();
                        foreach (var item in orders_group)
                        {
                            list.Add(new
                            {
                                users = item.GroupBy(m => m.OwnerId).Count(),
                                time = item.Count(),
                                totalMoney = item.Sum(m => m.Money),
                                date = item.Key
                            });
                        }
                        var result_list = PaginatedList<object>.Create(list, pe.page, 20);
                        return Ok(new
                        {
                            errcode = 0,
                            msg = "ok",
                            data = new
                            {
                                total = orders_group.Count(),
                                pageSize = 20,
                                list = result_list
                            }
                        });
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                }
            }
            catch (Exception ex)
            {
                return Ok(new { errcode = 1, msg = ex.ToString() });
            }
        }
    }
}